#include "packetmanager.h"

PacketManager::PacketManager(Api & api, QObject *parent)
	: QObject(parent), _api(api)
{
	initInterpreters();
}

PacketManager::~PacketManager()
{

}

void										PacketManager::initInterpreters()
{
	addInterpreter((byte)MAIN, (AInterpreter*)new MainInterpreter(_api, this));
}

void										PacketManager::addInterpreter(byte proto, AInterpreter *itpt)
{
	_itptMap[proto].push_back(itpt);
}

byte										PacketManager::getProto(Packet &pkg)
{
	return (*pkg.getData<byte>(1));
}

void										PacketManager::interpret(Packet &pkg)
{
	std::list<AInterpreter*>::iterator it;

	byte proto = getProto(pkg);

	if (_itptMap.count(proto) > 0)
	{
		for (it = _itptMap[proto].begin(); it != _itptMap[proto].end(); ++it)
			if ((*it)->interpret(pkg))
				break;
	}
	else
		qDebug() << "Proto not linked";

	// put pkg in collector
}

Packet										*PacketManager::buildPacket(byte proto, byte op)
{
	Packet									*pkg = new Packet;

	pkg->init();
	pkg->pushData<byte>(&proto);
	pkg->pushData<byte>(&op);
	return pkg;
}